/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useMemo, useRef, useState } from "react";
import {
  Button,
  Card,
  DatePicker,
  Form,
  Input,
  Modal,
  Select,
  Space,
  Table,
  Tag,
  message,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import "./Classify.scss";

interface TypeRow {
  id: number;
  code: string;
  name: string;
  order: number;
  status: "启用" | "停用";
  remark?: string;
  operator: string;
  operateTime: string;
  children?: TypeRow[];
}

const treeDataDefault: TypeRow[] = [
  {
    id: 1,
    code: "HPLXBH1859",
    name: "电子产品",
    order: 1,
    status: "启用",
    operator: "曹曙",
    operateTime: "2025-09-23 15:33:46",
    children: [
      {
        id: 2,
        code: "HPLXBH301",
        name: "手机",
        order: 2,
        status: "停用",
        operator: "九宾实",
        operateTime: "2025-09-23 15:33:46",
        children: [
          {
            id: 3,
            code: "HPLXBH2087",
            name: "智能手机",
            order: 3,
            status: "启用",
            operator: "应鹏鲲",
            operateTime: "2025-09-23 15:33:46",
          },
          {
            id: 4,
            code: "HPLXBH5856",
            name: "功能手机",
            order: 4,
            status: "启用",
            operator: "贝代齐",
            operateTime: "2025-09-23 15:33:46",
          },
        ],
      },
      {
        id: 5,
        code: "HPLXBH9082",
        name: "电视",
        order: 5,
        status: "启用",
        operator: "乾娴雅",
        operateTime: "2025-09-23 15:33:46",
        children: [
          {
            id: 6,
            code: "HPLXBH2106",
            name: "智能电视",
            order: 6,
            status: "启用",
            operator: "错叉菌",
            operateTime: "2025-09-23 15:33:46",
          },
        ],
      },
      {
        id: 7,
        code: "HPLXBH4489",
        name: "显示器",
        order: 7,
        status: "启用",
        operator: "萧文惠",
        operateTime: "2025-09-23 15:33:46",
      },
    ],
  },
  {
    id: 8,
    code: "HPLXBH2706",
    name: "服装",
    order: 8,
    status: "启用",
    operator: "苦俊楚",
    operateTime: "2025-09-23 15:33:46",
    children: [
      {
        id: 9,
        code: "HPLXBH8660",
        name: "男装",
        order: 9,
        status: "启用",
        operator: "夏候绮玉",
        operateTime: "2025-09-23 15:33:46",
      },
      {
        id: 10,
        code: "HPLXBH308",
        name: "裤子",
        order: 10,
        status: "启用",
        operator: "尾弘化",
        operateTime: "2025-09-23 15:33:46",
      },
      {
        id: 11,
        code: "HPLXBH4190",
        name: "连衣裙",
        order: 11,
        status: "启用",
        operator: "羽慧晨",
        operateTime: "2025-09-23 15:33:46",
      },
      {
        id: 12,
        code: "HPLXBH4844",
        name: "裙子",
        order: 12,
        status: "启用",
        operator: "李建",
        operateTime: "2025-09-23 15:33:46",
      },
    ],
  },
];

// 递归过滤树（保留匹配子节点的父节点）
function filterTree(
  nodes: TypeRow[],
  predicate: (n: TypeRow) => boolean
): TypeRow[] {
  const res: TypeRow[] = [];
  for (const n of nodes) {
    const children = n.children ? filterTree(n.children, predicate) : undefined;
    if (predicate(n) || (children && children.length)) {
      res.push({ ...n, children });
    }
  }
  return res;
}

// 递归严格过滤（仅自身匹配才保留，不保留不匹配的父级）
function filterTreeStrict(
  nodes: TypeRow[],
  predicate: (n: TypeRow) => boolean
): TypeRow[] {
  const res: TypeRow[] = [];
  for (const n of nodes) {
    const keep = predicate(n);
    const children = n.children
      ? filterTreeStrict(n.children, predicate)
      : undefined;
    if (keep) {
      res.push({ ...n, children });
    } else if (children && children.length) {
      // 子级匹配但父级不匹配时，不保留父级，仅保留子级（提到上一层）
      res.push(...children);
    }
  }
  return res;
}

// 递归插入到指定parentId；parentId为null则插入根
function insertNode(
  list: TypeRow[],
  parentId: number | null,
  node: TypeRow
): TypeRow[] {
  if (parentId == null) return [...list, node];
  return list.map((n) =>
    n.id === parentId
      ? { ...n, children: (n.children || []).concat(node) }
      : {
          ...n,
          children: n.children
            ? insertNode(n.children, parentId, node)
            : n.children,
        }
  );
}

// 展平树
function flatten(nodes: TypeRow[]): TypeRow[] {
  const arr: TypeRow[] = [];
  const walk = (ns: TypeRow[]) => {
    ns.forEach((n) => {
      arr.push(n);
      if (n.children) walk(n.children);
    });
  };
  walk(nodes);
  return arr;
}

// 递归更新/删除
function updateNode(
  list: TypeRow[],
  id: number,
  patch: Partial<TypeRow>
): TypeRow[] {
  return list.map((n) =>
    n.id === id
      ? { ...n, ...patch }
      : {
          ...n,
          children: n.children ? updateNode(n.children, id, patch) : n.children,
        }
  );
}
function removeNode(list: TypeRow[], id: number): TypeRow[] {
  return list
    .filter((n) => n.id !== id)
    .map((n) => ({
      ...n,
      children: n.children ? removeNode(n.children, id) : n.children,
    }));
}

export default function Classify() {
  const [form] = Form.useForm();
  const [data, setData] = useState<TypeRow[]>(treeDataDefault);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // 查询状态
  const [query, setQuery] = useState<any>({});

  // 新增/编辑相关
  const [addOpen, setAddOpen] = useState(false);
  const [addForm] = Form.useForm();
  const [editOpen, setEditOpen] = useState(false);
  const [editForm] = Form.useForm();
  const [editingId, setEditingId] = useState<number | null>(null);

  const fileInputRef = useRef<HTMLInputElement>(null);

  const filtered = useMemo(() => {
    const { keyword, status, operator } = query;
    // 先对关键字/操作人做包含筛选（保留父级）
    const basePred = (n: TypeRow) =>
      (keyword ? n.name.includes(keyword) || n.code.includes(keyword) : true) &&
      (operator ? n.operator.includes(operator) : true);
    let temp = filterTree(data, basePred);
    // 再对状态做严格筛选：仅自身匹配的节点保留
    if (status) {
      temp = filterTreeStrict(temp, (n) => n.status === status);
    }
    return temp;
  }, [data, query]);

  const columns: ColumnsType<TypeRow> = [
    { title: "序号", dataIndex: "id", width: 60, align: "center" },
    { title: "货品类型编码", dataIndex: "code", width: 180 },
    { title: "货品类型名称", dataIndex: "name", width: 260 },
    { title: "排序", dataIndex: "order", width: 80, align: "center" },
    {
      title: "状态",
      dataIndex: "status",
      width: 100,
      align: "center",
      render: (v) => <Tag color={v === "启用" ? "green" : "default"}>{v}</Tag>,
    },
    { title: "备注", dataIndex: "remark", width: 220 },
    { title: "操作人", dataIndex: "operator", width: 120 },
    { title: "操作时间", dataIndex: "operateTime", width: 200 },
    {
      title: "操作",
      key: "op",
      width: 120,
      render: (_, row) => (
        <Space>
          <Button type="link" size="small" onClick={() => openEdit(row)}>
            编辑
          </Button>
          <Button type="link" size="small" onClick={() => onDelete(row)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 查询按钮
  const onSearch = () => setQuery(form.getFieldsValue());

  // 新增
  const openAdd = () => {
    addForm.resetFields();
    setAddOpen(true);
  };
  const submitAdd = async () => {
    const values = await addForm.validateFields();
    const node: TypeRow = {
      id: Date.now(),
      code: values.code,
      name: values.name,
      order: values.order ?? 0,
      status: values.status,
      remark: values.remark,
      operator: values.operator || "系统",
      operateTime: new Date().toISOString().replace("T", " ").slice(0, 19),
    };
    setData((old) => insertNode(old, values.parentId ?? null, node));
    setAddOpen(false);
    message.success("新增成功");
  };

  // 编辑
  const openEdit = (row: TypeRow) => {
    setEditingId(row.id);
    editForm.setFieldsValue({
      code: row.code,
      name: row.name,
      order: row.order,
      status: row.status,
      remark: row.remark,
      operator: row.operator,
    });
    setEditOpen(true);
  };
  const submitEdit = async () => {
    const values = await editForm.validateFields();
    if (editingId == null) return;
    setData((old) =>
      updateNode(old, editingId, {
        code: values.code,
        name: values.name,
        order: values.order ?? 0,
        status: values.status,
        remark: values.remark,
        operator: values.operator,
        operateTime: new Date().toISOString().replace("T", " ").slice(0, 19),
      })
    );
    setEditOpen(false);
    message.success("编辑成功");
  };

  // 删除
  const onDelete = (row: TypeRow) => {
    Modal.confirm({
      title: `确认删除 “${row.name}” ?`,
      onOk: () => {
        setData((old) => removeNode(old, row.id));
        message.success("删除成功");
      },
    });
  };

  // 导入（JSON）
  const triggerImport = () => fileInputRef.current?.click();
  const onFileChange: React.ChangeEventHandler<HTMLInputElement> = async (
    e
  ) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const text = await file.text();
    try {
      const list: Partial<TypeRow>[] = JSON.parse(text);
      const toAdd: TypeRow[] = list.map((it, idx) => ({
        id: Date.now() + idx,
        code: String(it.code || ""),
        name: String(it.name || ""),
        order: Number(it.order || 0),
        status: (it.status as any) === "停用" ? "停用" : "启用",
        remark: it.remark || "",
        operator: String(it.operator || "导入"),
        operateTime: new Date().toISOString().replace("T", " ").slice(0, 19),
      }));
      setData((old) => [...old, ...toAdd]);
      message.success(`导入成功，共 ${toAdd.length} 条`);
    } catch (err) {
      message.error("导入失败：请提供JSON数组");
    } finally {
      if (fileInputRef.current) fileInputRef.current.value = "";
    }
  };

  // 导出 CSV
  const exportCSV = () => {
    const rows = flatten(filtered);
    const header = [
      "序号",
      "货品类型编码",
      "货品类型名称",
      "排序",
      "状态",
      "备注",
      "操作人",
      "操作时间",
    ];
    const lines = [header.join(",")].concat(
      rows.map((r) =>
        [
          r.id,
          r.code,
          r.name,
          r.order,
          r.status,
          r.remark || "",
          r.operator,
          r.operateTime,
        ].join(",")
      )
    );
    const blob = new Blob(["\ufeff" + lines.join("\n")], {
      type: "text/csv;charset=utf-8;",
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "货品类型.csv";
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="goods-type-page">
      <Card className="search-filter" variant="outlined">
        <Form
          form={form}
          layout="inline"
          className="filter-inline" // Added class for single-line layout
          onValuesChange={(_, allValues) => {
            setQuery(allValues);
          }}
          onFinish={onSearch}>
          <Form.Item label="货品类型" name="keyword">
            <Input
              placeholder="请输入类型名称/编码"
              allowClear
              style={{ width: 200 }}
            />
          </Form.Item>
          <Form.Item label="状态" name="status">
            <Select
              allowClear
              placeholder="请选择"
              style={{ width: 110 }}
              options={[
                { label: "启用", value: "启用" },
                { label: "停用", value: "停用" },
              ]}
            />
          </Form.Item>
          <Form.Item label="操作人" name="operator">
            <Input placeholder="请输入" allowClear style={{ width: 130 }} />
          </Form.Item>
          <Form.Item label="操作时间" name="operateTime">
            <DatePicker.RangePicker style={{ width: 220 }} />
          </Form.Item>
          <Space className="filter-actions">
            <Button
              onClick={() => {
                form.resetFields();
                setQuery({});
              }}>
              重置
            </Button>
            <Button type="primary" onClick={onSearch}>
              查询
            </Button>
          </Space>
        </Form>
      </Card>

      <Card className="action-buttons" variant="outlined">
        <Space>
          <Button type="primary" onClick={openAdd}>
            新增
          </Button>
          <Button onClick={triggerImport}>导入</Button>
          <input
            ref={fileInputRef}
            type="file"
            accept="application/json"
            style={{ display: "none" }}
            onChange={onFileChange}
          />
          <Button onClick={exportCSV}>导出</Button>
        </Space>
      </Card>

      <Card className="store-table" variant="outlined">
        <Table
          rowKey="id"
          size="middle"
          columns={columns}
          dataSource={filtered}
          expandable={{
            defaultExpandAllRows: true,
            expandIconColumnIndex: columns.findIndex(
              (c: any) => c.dataIndex === "name"
            ),
            expandRowByClick: true,
          }}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
            checkStrictly: false,
          }}
          pagination={false}
        />
      </Card>

      {/* 新增 */}
      <Modal
        open={addOpen}
        title="新增类型"
        onOk={submitAdd}
        onCancel={() => setAddOpen(false)}
        destroyOnHidden>
        <Form form={addForm} preserve={false} labelCol={{ span: 6 }}>
          <Form.Item label="上级类型" name="parentId">
            <Select
              allowClear
              placeholder="不选则为顶级"
              options={flatten(data).map((n) => ({
                label: n.name,
                value: n.id,
              }))}
            />
          </Form.Item>
          <Form.Item
            label="编码"
            name="code"
            rules={[{ required: true, message: "请输入编码" }]}>
            <Input />
          </Form.Item>
          <Form.Item
            label="名称"
            name="name"
            rules={[{ required: true, message: "请输入名称" }]}>
            <Input />
          </Form.Item>
          <Form.Item label="排序" name="order">
            <Input type="number" />
          </Form.Item>
          <Form.Item
            label="状态"
            name="status"
            initialValue={"启用"}
            rules={[{ required: true }]}>
            <Select
              options={[
                { label: "启用", value: "启用" },
                { label: "停用", value: "停用" },
              ]}
            />
          </Form.Item>
          <Form.Item label="备注" name="remark">
            <Input />
          </Form.Item>
          <Form.Item label="操作人" name="operator">
            <Input />
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑 */}
      <Modal
        open={editOpen}
        title="编辑类型"
        onOk={submitEdit}
        onCancel={() => setEditOpen(false)}
        destroyOnHidden>
        <Form form={editForm} preserve={false} labelCol={{ span: 6 }}>
          <Form.Item
            label="编码"
            name="code"
            rules={[{ required: true, message: "请输入编码" }]}>
            <Input />
          </Form.Item>
          <Form.Item
            label="名称"
            name="name"
            rules={[{ required: true, message: "请输入名称" }]}>
            <Input />
          </Form.Item>
          <Form.Item label="排序" name="order">
            <Input type="number" />
          </Form.Item>
          <Form.Item label="状态" name="status" rules={[{ required: true }]}>
            <Select
              options={[
                { label: "启用", value: "启用" },
                { label: "停用", value: "停用" },
              ]}
            />
          </Form.Item>
          <Form.Item label="备注" name="remark">
            <Input />
          </Form.Item>
          <Form.Item label="操作人" name="operator">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
